package dao;

import utils.DbHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * -*- coding: utf-8 -*-
 *
 * @Author: LZN
 * @Date: 2023/3/12 0012 20:57
 * @Description:
 */
public class UserDao {
    /**
     * 登陆功能
     *
     * @param username
     * @param password
     * @return
     */
    public boolean login(String username, String password) {
        Connection conn = DbHelper.getConnection();
        PreparedStatement pst = null;
        ResultSet rst = null;
        boolean checker = false;
        String sql = "SELECT * FROM user WHERE username=? AND password=?";
        try {
            pst = conn.prepareStatement(sql);
            pst.setString(1, username);
            pst.setString(2, password);
            rst = pst.executeQuery();
            if (rst.next()) {
                checker = true;
            } else {
                checker = false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        DbHelper.close(pst, rst);
        return checker;
    }

    /**
     * 注册功能
     *
     * @param username
     * @param password
     * @return
     */
    public boolean register(String username, String password) {
        Connection conn = DbHelper.getConnection();
        PreparedStatement pst = null;
        boolean rChecker = false;
        String sql = "INSERT INTO user(username,password) VALUES(?,?)";
        if (!this.registerCheck(username)) {
            try {
                pst = conn.prepareStatement(sql);
                pst.setString(1, username);
                pst.setString(2, password);
                pst.executeUpdate();
            } catch (Exception e) {
                e.printStackTrace();
            }
            rChecker = true;
        } else {
            rChecker = false;
        }
        DbHelper.close(pst, null);
        return rChecker;
    }

    /**
     * 判断名为username的用户是否已在表中存在，存在则返回false
     *
     * @param username
     * @return
     */
    public boolean registerCheck(String username) {
        Connection conn = DbHelper.getConnection();
        PreparedStatement pst = null;
        ResultSet rst = null;
        boolean checker = false;
        String sql = "SELECT * FROM user WHERE username=?";
        try {
            pst = conn.prepareStatement(sql);
            pst.setString(1, username);
            rst = pst.executeQuery();
            if (rst.next()) {
                DbHelper.close(pst, rst);
                checker = true;
            } else {
                DbHelper.close(pst, rst);
                checker = false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return checker;
    }
}

